<script lang="js" setup>
import { mainnet, arbitrum } from '@wagmi/core/chains'
import {
  createWeb3Modal,
  defaultWagmiConfig,
  useWeb3Modal,
  useWeb3ModalEvents,
  useWeb3ModalState,
  useWeb3ModalTheme
} from '@web3modal/wagmi/vue'
import { sendTransaction, prepareSendTransaction } from '@wagmi/core'
import { parseEther } from 'viem'
import { waitForTransaction } from '@wagmi/core'

// @ts-expect-error 1. Get projectId
const projectId = import.meta.env.VITE_PROJECT_ID
if (!projectId) {
  throw new Error('VITE_PROJECT_ID is not set')
}

console.log(projectId, 'dsd')

// 2. Create wagmiConfig

const chains = [mainnet, arbitrum]
const wagmiConfig = defaultWagmiConfig({
  chains,
  projectId,
  metadata: {
    name: 'Web3Modal Vue Example'
  }
})

// 3. Create modal
createWeb3Modal({
  wagmiConfig,
  projectId,
  chains,
  themeMode: 'light',
  themeVariables: {
    '--w3m-color-mix': '#00BB7F',
    '--w3m-color-mix-strength': 20
  }
})

// 4. Use modal composable
const modal = useWeb3Modal()
const state = useWeb3ModalState()
const { setThemeMode, themeMode, themeVariables } = useWeb3ModalTheme()
const events = useWeb3ModalEvents()

// 发起交易
const toSendTransaction = async () => {
  const config = await prepareSendTransaction({
    to: 'moxey.eth',
    value: parseEther('0.01')
  })

  // 交易hash
  const { hash } = await sendTransaction(config)
  console.log('交易hash', hash)

  const data = await waitForTransaction({
    hash
  })
  console.log('等待交易结果', data)
}


</script>

<template>
<!--  <w3m-button />-->
<!--  <w3m-network-button />-->
<!--  <w3m-connect-button />-->
<!--  <w3m-account-button />-->

  <button @click="modal.open()">Open Connect Modal</button>
  <button @click="modal.open({ view: 'Networks' })">Open Network Modal</button>
  <button @click="setThemeMode(themeMode === 'dark' ? 'light' : 'dark')">Toggle Theme Mode</button>
  <button @click="toSendTransaction()">发起交易</button>
  <pre>{{ JSON.stringify(state, null, 2) }}</pre>
  <pre>{{ JSON.stringify({ themeMode, themeVariables }, null, 2) }}</pre>
  <pre>{{ JSON.stringify(events, null, 2) }}</pre>
</template>
